package i2.application.fmw.validators;

import i2.application.fmw.validators.annotations.Unique;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class UniqueValidator implements ConstraintValidator<Unique, String> {

	@PersistenceContext
	private EntityManager entityManager;
	
	@Override
	public void initialize(Unique constraintAnnotation) {
		
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		if (value == null) {
			return false;
		}
		
		Query query = entityManager.createNamedQuery("isUnique");
		
		if (query.getSingleResult() == null) {
			return true;
		}
		return false;
	}

	public void setEntityManager(EntityManager em) {
		this.entityManager = em;
	}
	
	
	
}
